package cn.zzuli.datastoredemo;

import androidx.appcompat.app.AppCompatActivity;
import androidx.core.os.EnvironmentCompat;

import android.content.ContentResolver;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.provider.Settings;
import android.text.format.DateUtils;
import android.view.View;
import android.widget.Toast;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.Date;

public class MainActivity extends AppCompatActivity {

    private static final int REQUEST_SETTINGS_CODE = 123;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        /**
         * Android 11 新增的权限，如果使用，请使用下面代码申请权限
         * <uses-permission android:name="android.permission.MANAGE_EXTERNAL_STORAGE"
         *         tools:ignore="ScopedStorage" />
         */
        //判断是否授予权限，没有则进行申请
//        if(!Environment.isExternalStorageManager()){
//            Intent intent = new Intent(Settings.ACTION_MANAGE_APP_ALL_FILES_ACCESS_PERMISSION);
//            //intent.setData(Uri.parse("package:$packageName"));
//            intent.setData(Uri.parse("package:"+getPackageName()));
//            startActivityForResult(intent, REQUEST_SETTINGS_CODE);
//        }

        new Thread(){
            @Override
            public void run() {
                //下载图片
                Bitmap image = getImage("https://n.sinaimg.cn/sinakd2021424s/77/w1000h677/20210424/7a11-kpamyii9478718.jpg");
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        //保存图片
                        saveImageToGallery2(MainActivity.this,image);
                    }
                });
            }
        }.start();
    }
    //下载网络图片
    public Bitmap getImage(String path){
        try {
            HttpURLConnection cn= (HttpURLConnection) new URL(path).openConnection();
            InputStream stream = cn.getInputStream();
            return BitmapFactory.decodeStream(stream);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }
    /**
     * android 11及以上保存图片到相册
     * @param context
     * @param image
     */
    public static void saveImageToGallery2(Context context, Bitmap image){
        long mImageTime = System.currentTimeMillis();
        String imageDate = new SimpleDateFormat("yyyyMMdd-HHmmss").format(new Date(mImageTime));
        String SCREENSHOT_FILE_NAME_TEMPLATE = "zzuli_%s.jpg";//图片名称，以"zzuli"+时间戳命名
        String mImageFileName = String.format(SCREENSHOT_FILE_NAME_TEMPLATE, imageDate);

        final ContentValues values = new ContentValues();
        values.put(MediaStore.MediaColumns.RELATIVE_PATH, Environment.DIRECTORY_PICTURES
                + File.separator + "zzuli"); //Environment.DIRECTORY_SCREENSHOTS:截图,图库中显示的文件夹名。"zzuli"
        values.put(MediaStore.MediaColumns.DISPLAY_NAME, mImageFileName);
        values.put(MediaStore.MediaColumns.MIME_TYPE, "image/jpeg");
        values.put(MediaStore.MediaColumns.DATE_ADDED, mImageTime / 1000);
        values.put(MediaStore.MediaColumns.DATE_MODIFIED, mImageTime / 1000);
        values.put(MediaStore.MediaColumns.DATE_EXPIRES, (mImageTime + DateUtils.DAY_IN_MILLIS) / 1000);
        values.put(MediaStore.MediaColumns.IS_PENDING, 1);

        ContentResolver resolver = context.getContentResolver();
        final Uri uri = resolver.insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
        try {
            // First, write the actual data for our screenshot
            try (OutputStream out = resolver.openOutputStream(uri)) {
                if (!image.compress(Bitmap.CompressFormat.JPEG, 100, out)) {
                    throw new IOException("Failed to compress");
                }
            }
            // Everything went well above, publish it!
            values.clear();
            values.put(MediaStore.MediaColumns.IS_PENDING, 0);
            values.putNull(MediaStore.MediaColumns.DATE_EXPIRES);
            resolver.update(uri, values, null, null);
        }catch (IOException e){
            resolver.delete(uri, null);
        }
    }

    public void fileWrite(View view) {
        FileOutputStream outputStream=null;
        try {
            outputStream = openFileOutput("hello.txt", MODE_PRIVATE);
            outputStream.write("hello Android!".getBytes());
            outputStream.close();
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            if(outputStream!=null){
                try {
                    outputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    public void fileRead(View view) {
        FileInputStream inputStream =null;
        try {
            inputStream = openFileInput("hello.txt");
            byte[] bytes = new byte[1024];
            int len = inputStream.read(bytes);
            inputStream.close();
            String str = new String(bytes, 0, len);
            System.out.println(str);
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            if(inputStream!=null){
                try {
                    inputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    public void sdFileWrite(View view) {
        File file = Environment.getExternalStorageDirectory();
        System.out.println(file.getAbsolutePath());
        File filesDir = getExternalFilesDir(null);
        System.out.println(filesDir.getAbsolutePath());
        File filesDir1 = getFilesDir();
        System.out.println(filesDir1.getAbsolutePath());
        File file1 = new File(file, "111");
        File file2 = new File(filesDir, "222");
        File file3 = new File(filesDir1, "333");
        try {
//            FileOutputStream fileOutputStream = new FileOutputStream(file1);
//            fileOutputStream.write("11111111".getBytes());
//            fileOutputStream.close();
            FileOutputStream fileOutputStream = new FileOutputStream(file2);
            fileOutputStream.write("11111111".getBytes());
            fileOutputStream.close();
            fileOutputStream = new FileOutputStream(file3);
            fileOutputStream.write("11111111".getBytes());
            fileOutputStream.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void spWrite(View view) {
        //1.创建文件，第一个参数：文件名，
        // 第二个参数：文件模式，取值：MODE_PRIVATE（私有），MODE_APPEND(追加)
        SharedPreferences mysp = getSharedPreferences("mysp", MODE_PRIVATE);
        //2.获得编辑器
        SharedPreferences.Editor edit = mysp.edit();
        //3.添加数据
        edit.putString("name", "zhangsan");
        edit.putString("password", "123456");
        //4.提交，保存
        //edit.commit();
        edit.apply();//建议使用
    }

    public void spRead(View view) {
        //1.打开文件，第一个参数：文件名，
        // 第二个参数：文件模式，取值：MODE_PRIVATE（私有），MODE_APPEND(追加)
        SharedPreferences mysp = getSharedPreferences("mysp", MODE_PRIVATE);
        //2.读取数据
        String name = mysp.getString("name", "");
        String password = mysp.getString("password", "");
        Toast.makeText(this, "name:" + name + ",password:" + password,
                Toast.LENGTH_SHORT).show();
    }
}